import requests
from config import BASE_URL


# 封装接口类
class RegLogin(object):

    # 设置实例属性
    def __init__(self, session):
        # 定义session属性,创建接口类对象时传递进来
        self.__session = session  # session = requests.Session()
        self.__img_code_url = BASE_URL + "/common/public/verifycode1/{}"  # 图片验证码url
        self.__phone_code_url = BASE_URL + "/member/public/sendSms"  # 获取短信验证码url
        self.__reg_url = BASE_URL + "/member/public/reg"  # 注册url
        self.__login_url = BASE_URL + "/member/public/login"  # 登录url
        self.__status_url = BASE_URL + "/member/public/islogin"  # 获取登录状态url

    # 定义接口方法
    def get_img_code(self, random_num):
        """获取图片验证码接口"""
        # 发送requests请求
        res = self.__session.get(url=self.__img_code_url.format(random_num))
        # 返回响应结果
        return res

    def get_phone_code(self, req_data):
        """获取短信验证码接口"""
        # 请求头
        header = {"Content-Type": "application/x-www-form-urlencoded"}
        # 发送请求，此处用session对象发送post请求（不考虑cookie变化的问题）
        res = self.__session.post(url=self.__phone_code_url, headers=header, data=req_data)
        # 返回结果
        return res

    def register(self, req_data):
        """注册接口"""
        res = self.__session.post(url=self.__reg_url, data=req_data)
        return res

    def login(self, req_data):
        """登录接口"""
        res = self.__session.post(url=self.__login_url, data=req_data)
        return res

    def get_login_status(self):
        """获取登录状态接口"""
        res = self.__session.post(url=self.__status_url)
        return res


if __name__ == '__main__':
    # 创建对象
    session = requests.Session()
    reg = RegLogin(session)
    # 调用方法
    result = reg.get_img_code(123)
    data1 = {"phone": "13800005212",
             "imgVerifyCode": 8888,
             "type": "reg"}
    result1 = reg.get_phone_code(data1)
    # data2 = {"phone": "13800005212",
    #          "password": "Aa123456",
    #          "verifycode": 8888,
    #          "phone_code": 666666,
    #          "dy_server": "on",
    #          "invite_phone": ""}
    # result2 = reg.register(data2)
    data3 = {"keywords": "13800005212",
             "password": "Aa123456"}
    result3 = reg.login(data3)
    # 打印结果
    print(result3.text)
